package wsem.parser;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedHashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.mysql.jdbc.StringUtils;

import wsem.model.Query;
import wsem.utils.ConfigUtils;

public class QueryParser {

	private LinkedHashMap<String, Query> queries;

	public QueryParser() {
		queries = new LinkedHashMap<String, Query>();
	}

	public LinkedHashMap<String, Query> getQueries() {
		return queries;
	}

	public void parse() throws Exception {

		URL path = getClass().getClassLoader().getResource(
				ConfigUtils.PATH_QUERIES);

		final File queryFile = new File(path.getPath());

		/*
		 * Parsage des documents
		 */
		try {

			DocumentBuilderFactory fabrique = DocumentBuilderFactory
					.newInstance();

			DocumentBuilder constructeur = fabrique.newDocumentBuilder();

			Document document = constructeur.parse(queryFile);

			Node racineNode = document.getDocumentElement();

			parseNode(racineNode, null);
		} catch (Exception e) {
			System.out.println("Erreur parsage queries");
			throw e;
		}
	}

	/**
	 * Parse un noeud d'un document
	 * 
	 * @param docObj
	 * @param node
	 * @param xPath
	 * @throws Exception
	 */
	private void parseNode(Node node, Query query) throws Exception {

		// Si le noeud est une query
		if (node.getNodeName().equals("query")) {
			// Recuperation de l'identifiant de la requete
			NamedNodeMap attributes = node.getAttributes();
			Node idNode = attributes.getNamedItem("id");

			// Creation de la query
			query = new Query(idNode.getNodeValue());

		}
		// Si le noeud est un element text
		else if (node.getNodeName().equals("#text")) {

			String currentValue = node.getNodeValue();
			if (org.apache.commons.lang3.StringUtils.isNotBlank(currentValue)) {

				if (query != null) {
					query.setQueryValue(currentValue);
					queries.put(query.getIdQuery(), query);

					// Reinit req
					query = null;
				}

			}

		}

		// Parcours des elements fils
		NodeList nodesList = node.getChildNodes();
		for (int i = 0; i < nodesList.getLength(); ++i) {
			Node n = nodesList.item(i);
			parseNode(n, query);
		}
	}

	public static void main(String[] args) {

		QueryParser queryParse = new QueryParser();
		try {
			queryParse.parse();
		} catch (Exception e) {

			e.printStackTrace();
		}
	}

}
